import sys
import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QTimer
from pyqtgraph import GraphicsLayoutWidget, PlotCurveItem, mkPen
from pyqtgraph.graphicsItems.PlotItem import PlotItem


title_template = "Quadcopter Height Plot"
class RealtimePlotWidget(GraphicsLayoutWidget):
    
    def __init__(self, parent=None):
        super().__init__(parent)
        pg.setConfigOptions(antialias=True)
        
        # 设置背景主题为白色
        # self.setBackground('w')
        
        self.plot: PlotItem = self.addPlot(title=title_template)
        self.plot.showGrid(x=True, y=True, alpha=0.5)
        # 设定y轴范围为[0, 10]
        self.plot.setYRange(0, 10)
        # 禁用y轴鼠标拖拽
        self.plot.setMouseEnabled(x=True, y=False)
        
        self.__is_touch = False
        self.__timer: QTimer = None
        self.curve = PlotCurveItem(pen=mkPen(color='orange', width=2))
        self.plot.addItem(self.curve)
        self.target = PlotCurveItem(pen=mkPen(color='red', width=1))
        self.plot.addItem(self.target)
        
        # self.plot.enableAutoRange('x', 0.95)
        
        self.__x_arr = np.array([])
        self.__y_arr = np.array([])
        self.__x_current = 0
        self.__x_increment = 1
        # self.plot1: PlotItem = self.addPlot(title="Basic array plotting", y=np.random.normal(size=100))
        self.__y_target = np.array([])
        self.__y_value = 0
        
        
    def __update_ui(self):
        self.curve.setData(self.__x_arr, self.__y_arr)
            
        self.__y_target = np.full(len(self.__x_arr), self.__y_value)
        self.target.setData(self.__x_arr, self.__y_target)
        
        if not self.__is_touch:
            self.plot.setXRange(self.__x_current - 450, self.__x_current + 50)
            

    def update_plot(self, value: float):
        self.__x_arr = np.append(self.__x_arr, self.__x_current)
        self.__y_arr = np.append(self.__y_arr, value)
        self.__x_current += self.__x_increment
        # 截取self.__x_arr的末尾1000个数据
        self.__x_arr = self.__x_arr[-2000:]
        self.__y_arr = self.__y_arr[-2000:]
        
        self.plot.setLabel(axis='right', text="{:.2f}m".format(value))
        self.__update_ui()
        
    def update_target(self, value: float):
        self.__y_value = value
    
    def clear_data(self):
        self.__x_arr = np.array([])
        self.__y_arr = np.array([])
        self.__x_current = 0
        self.__x_increment = 5
        
        self.__y_target = np.array([])
        
        self.__update_ui()
        
    
    def __start_timer(self):
        if self.__timer is not None:
            return
        self.__timer = QTimer()
        # 3s后触发__touch_finished函数
        self.__timer.timeout.connect(self.__touch_finished)
        self.__timer.start(2000)

    def __stop_timer(self):
        if self.__timer is None:
            return
        self.__timer.stop()
        self.__timer.timeout.disconnect(self.__touch_finished)
        self.__timer = None

    def mousePressEvent(self, ev):
        super().mousePressEvent(ev)
        self.__stop_timer()
        self.__is_touch = True

    def mouseReleaseEvent(self, ev):
        super().mouseReleaseEvent(ev)
        self.__start_timer()

    def __touch_finished(self):
        self.__is_touch = False
        self.__stop_timer()
    
if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = RealtimePlotWidget()
    win.show()
    
    # 生成一个值在[0, 100]的随机数
    timer = QTimer()
    timer.timeout.connect(lambda: win.update_plot(np.random.uniform(0, 100)))
    timer.start(100)
    
    sys.exit(app.exec_())
